<?php

/*//. Pid3 (Pid Three)
../ ID3 v2.4 Conforming Tagging Library

This software is licensed under the BSD License.

Copyright (c) 2007, Bob Majdak Jr <bob@kateos.org>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

	* Redistributions of source code must retain the above copyright notice,
	this list of conditions and the following disclaimer.

	* Redistributions in binary form must reproduce the above copyright notice,
	this list of conditions and the following disclaimer in the documentation
	and/or other materials provided with the distribution.
      
	* Neither the name of the organization nor the names of its contributors
	may be used to endorse or promote products derived from this software
	without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
.//*/

define("ID3V2_VERSION","4.0");

define("ID3V2_HASFOOTER",16);
define("ID3V2_EXPERIMENTAL",32);
define("ID3V2_EXTHEAD",64);
define("ID3V2_UNSYNC",128);

define("ID3V2_ALTERTAG_SAVETAG",64);
define("ID3V2_ALTERFILE_SAVETAG",32);
define("ID3V2_TAG_READONLY",16);
define("ID3V2_TAG_GROUP",64);
define("ID3V2_TAG_COMPRESS",8);
define("ID3V2_TAG_ENCRYPT",4);
define("ID3V2_TAG_UNSYNC",2);
define("ID3V2_TAG_HASLENGTH",1);

define("BYTES_PER_BITE",1024);

$valid_tag_id = array(
	"TIT2" => "title",
	"TPE1" => "artist",
	"TALB" => "album",
	"TYER" => "year",
	"COMM" => "comment",
	"TRCK" => "track",
	"TCON" => "genre"
);

class frameID3v2 {
	public $id;
	public $syncsize;
}

function deSyncInt($int) {
	//. this should be good for a few laughs.
	$binrep = decbin($int);
	while(strlen($binrep) < 32) { $binrep = "0" . $binrep; }
	if(preg_match("/0([01]{7})0([01]{7})0([01]{7})0([01]{7})$/",$binrep,$bin)) {
		return bindec("0000".$bin[1].$bin[2].$bin[3].$bin[4]);
	} else {
		return 0;
	}
}

function goSyncInt($int) {
	$binrep = decbin($int);
	while(strlen($binrep) < 32) { $binrep = "0" . $binrep; }
	preg_match("/0000([01]{7})([01]{7})([01]{7})([01]{7})$/",$binrep,$bin);
	if(!$bin[0]) { die("unable to safesync"); }
	return bindec("0".$bin[1]."0".$bin[2]."0".$bin[3]."0".$bin[4]);
}

function binSyncInt($int) {
	$binrep = decbin($int);
	while(strlen($binrep) < 32) { $binrep = "0" . $binrep; }
	preg_match("/([01]{8})([01]{8})([01]{8})([01]{8})$/",$binrep,$bin);
	return chr(bindec($bin[1])).chr(bindec($bin[2])).chr(bindec($bin[3])).chr(bindec($bin[4]));
}

function readID3v2($filename) {

	clearstatcache();

	$p = fopen($filename,"rb");

	$tag->TAG = pack("a3",fread($p,3));
	if($tag->TAG == "ID3") {

		$tag->ver_maj = ord(fread($p,1));
		$tag->ver_min = ord(fread($p,1));

		if((float)sprintf("%d.%d",$tag->ver_maj,$tag->ver_min) > ID3V2_VERSION) {
			return 1;
//			die("ID3v2 Tag Found, but unable to parse. File contains updated tag (ID3v2.".$tag->ver_maj.".".$tag->ver_min." > ID3v2.".ID3V2_VERSION.").");
		}

		$tag->flag = ord(fread($p,1));

		if($tag->flag & ID3V2_EXTHEAD) {
			return 1;
//			die("Tag contains an extended header, unable to parse that at this time.");
			//. WELL WHY NOT, BOB
			//. because i do not have any mp3's with one to test on. send me one and
			//. i will.
		}

		$unpack = unpack("N",fread($p,4));
		$tag->syncsize = $unpack[1];
		$tag->size = deSyncInt($tag->syncsize);
		$tag->total_size = $tag->size + 10;

		while(ftell($p) < $tag->total_size) {
			$frame = null; $frame = new frameID3v2;
			$frame->id = fread($p,4);
			if(!preg_match("/[A-Z0-9]{4}/",$frame->id)) {
				$frame = null; $frame = new frameID3v2; 
				$tag->padding = $tag->size - ftell($p);
				fseek($p,$tag->total_size);
			} else {
				$unpack = unpack("N",fread($p,4));
				$frame->syncsize = $unpack[1];				
				$frame->size = deSyncInt($frame->syncsize);
				$frame->flag_set1 = ord(fread($p,1));
				$frame->flag_set2 = ord(fread($p,1));
				$frame->data = @fread($p,$frame->size);
			}

			if($frame->id) {
				$tag->frame[] = $frame;
			}
		}

	} else {
		return 1;
//		die("No ID3v2 Tag Found.");
	}

	unset($null);
	fclose($p);
	return $tag;

}

function writeID3v2($filename,$data) {

	clearstatcache();

	global $valid_tag_id;

	fixID3v2TagSize($filename);
	$oldtag = readID3v2($filename);
	if(!is_object($oldtag)) {
		$oldtag = new StdClass;
		$oldtag->TAG = '';
		$oldtag->total_size = 0;
		$oldtag->size = 0;
	}

	$tag = new StdClass;
	$tag->TAG = "ID3";
	$tag->ver_maj = 4;
	$tag->ver_min = 0;
	$tag->flag = 0;
	$tag->syncsize = 0;
	$tag->size = 0;
	$tag->total_size = $tag->size + 10;

	foreach($valid_tag_id as $tid => $type) {
		unset($frame);
		if($data[$type]) {
			$frame->id = $tid;
			$frame->syncsize = 0;
			$frame->size = 0;
			$frame->flag_set1 = 0;
			$frame->flag_set2 = 0;
			$frame->data = chr(0).$data[$type].chr(0);

			$frame->size = strlen($frame->data);
			$frame->syncsize = goSyncInt($frame->size);

			$tag->frame[] = $frame;
			$tag->size += $frame->size + 10;
			$tag->total_size += $frame->size + 10;
			$tag->syncsize = goSyncInt($tag->size);

		}
	}

	$binpad = '';
	$bindata = '';
	if($tag->total_size > $oldtag->total_size) {
//		printf("new tag larger. adding 64 bytes of padding.\n");
		$tag->size += 64;
		$tag->total_size += 64;
		$tag->syncsize = goSyncInt($tag->size);
		for($a = 0; $a < 64; $a++) {
			$binpad .= chr(0);
		}
	} else {
//		printf("new tag smaller. padding %d bytes to fit %d.\n",($oldtag->total_size - $tag->total_size),$oldtag->total_size);
		for($a = 0; $a < ($oldtag->total_size - $tag->total_size); $a++) {
			$binpad .= chr(0);
		}
		$tag->size += ($oldtag->total_size - $tag->total_size);
		$tag->total_size += ($oldtag->total_size - $tag->total_size);
		$tag->syncsize = goSyncInt($tag->size);
	}

	$binhead = $tag->TAG . chr($tag->ver_maj) . chr($tag->ver_min) . chr($tag->flag) . binSyncInt($tag->syncsize);

	foreach($tag->frame as $frame) {
		$binframe = $frame->id . binSyncInt($frame->syncsize) . chr($frame->flag_set1) . chr($frame->flag_set2);
		$binframe .= $frame->data;
		$bindata .= $binframe;
	}

	$bintag = $binhead . $bindata . $binpad;

	if(strlen($bintag) != $tag->total_size) {
		printf("bad tag build (%d bytes vs expected %d.)\n",strlen($bintag),$tag->total_size);
		die();
	}

	if($tag->total_size > $oldtag->total_size) {
		if($oldtag->TAG) {
			stripID3v2($filename);
		}

		$tempfilename = str_replace(basename($filename),"",$filename) . time() . ".pgid3";
		if(!touch($tempfilename)) {
			printf("Unable to modify. Check filesytem permissions.\n");
			return 1;
		}

		$rp = fopen($filename,"rb");
		fseek($rp,$oldtag->size,SEEK_SET);

		$tp = fopen($tempfilename,"w");

		fwrite($tp,$bintag,$tag->total_size);

		while(!feof($rp)) {
			fwrite($tp,fread($rp,BYTES_PER_BITE),BYTES_PER_BITE);
		}

		fclose($rp);
		fclose($tp);

		unlink($filename); //. gulp
		rename($tempfilename,$filename);
		touch($filename);

	} else {

		$p = fopen($filename,"r+b");
		fwrite($p,$bintag,$tag->total_size);
		fclose($p);

	}

}

function translateID3v2($frame) {

	global $valid_tag_id;

	$output = array();	
	
	if(!$frame) {
		return;
	}
	foreach($frame as $data) {
		if(array_key_exists($data->id,$valid_tag_id)) {
			$output[$valid_tag_id[$data->id]] = str_replace(chr(0),"",$data->data);
		}
	}

	return $output;

}

function fixID3v2TagSize($filename) {

	$tag = readID3v2($filename);
	if(!is_object($tag) || !array_key_exists('TAG',$tag) || !$tag->TAG) { return 0; }
//	printf("tag says %d bytes long.\n",$tag->total_size);
	$p = fopen($filename,"rb");
	fseek($p,$tag->total_size);
	while(1) {
		$char = fgetc($p);
		if($char == chr(0)) {
			//. a null byte? extra padding not accounted for by size.

			//. what if we run into a borked winamp one, where they pad with
			//. chr 32 instead because they were dumb. chances are this only
			//. fixes problems caused by MY previous id3v2 library. :p

		} else {

//			printf("byte (%d)... ",ftell($p));
			if($char == chr(255)) {
				//. this might be the first mp3 sync block.
//				printf("solid byte... ");
				$subchar = ord(fgetc($p));
				if(
					(($subchar & 240) == 240) &&			//. 11110000 end of sync.
					(($subchar & 6) == 2) &&				//. 00000010 layer 3.
					(($subchar & 8) == 8)				//. 00001000 mpeg 1.
				) {
					$yetsubchar = ord(fgetc($p));
					if(
						(($yetsubchar & 240) != 240) && 	//. 11110000 invalid bitrate.
						(($yetsubchar & 12) != 12) 		//. 00001100 invalid sample rate.
					) {
//						printf("mp3 sync. (%s / %s / %s)\n",decbin(ord($char)),decbin($subchar),decbin($yetsubchar));
						fseek($p,-3,SEEK_CUR);
						break;
					}
					fseek($p,-1,SEEK_CUR);
				}
				fseek($p,-1,SEEK_CUR);
			}
//			printf("false.\n");
		}
	}
	$newlen = ftell($p);
	fclose($p);

	if($newlen > $tag->total_size) {
		printf("first mp3 sync at %d (preceeding corruption %d bytes).\n",$newlen,($newlen - $tag->total_size));
		$p = fopen($filename,"r+b");
		fseek($p,6,SEEK_SET);

		$safeint = goSyncInt($newlen - 10);
		$bindat = binSyncInt($safeint);
		printf("writing new size of %d (ss %d) (start %d).\n",$newlen,$safeint,ftell($p));
		fwrite($p,$bindat,4);
		fclose($p);
	} else {
//		echo("tag appears to be ok (in this respect).\n");
	}

}

function stripID3v2($filename) {

	clearstatcache();

	$tempfilename = str_replace(basename($filename),"",$filename) . time() . ".pgid3";
	touch($tempfilename);

	fixID3v2TagSize($filename);

	$tag = readID3v2($filename);
	if(!is_object($tag) || !$tag->TAG) { return 0; }

	$rp = fopen($filename,"rb");
	fseek($rp,$tag->total_size,SEEK_SET);

	$tp = fopen($tempfilename,"w");

	//. this seemed to be speedy, reading 32 bytes a time.
	//. except this seems slow on windows.
	//. 1024 seems pretty good on large files, at about 2 seconds to do.
	while(!feof($rp)) {
		fwrite($tp,fread($rp,BYTES_PER_BITE),BYTES_PER_BITE);
	}

	fclose($rp);
	fclose($tp);

	unlink($filename);
	rename($tempfilename,$filename);
	touch($filename);

	return 0;
	//unlink($tempfilename);
}

?>